package com.it.jasypt.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SensitiveDataCommonSerializer extends JsonSerializer<String> {
    // 定义脱敏规则：正则表达式 -> 替换模板
    private static final Map<String, String> MASK_RULES = new HashMap<String, String>() {{
        // 精确匹配规则
        put("(\\d{3})\\d{11}(\\d{4})", "$1***********$2");  // 身份证号
        put("(\\d{3})\\d{4}(\\d{4})", "$1****$2");         // 手机号
        put("(\\w{3})\\w*(@.*)", "$1****$2");              // 邮箱

        put(".*", "****");   // 兜底默认规则（匹配所有字符串）;
    }};

    // 通用脱敏方法

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        String result = null;
        for (Map.Entry<String, String> entry : MASK_RULES.entrySet()) {
            String regex = entry.getKey();
            String replacement = entry.getValue();
            if (value.matches(regex)) {
                result = value.replaceAll(regex, replacement);
                break;
            }
        }
        gen.writeString(result);
    }
}